package com.chen.interceptors;

import com.chen.common.utils.JwtUtil;
import com.chen.common.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.*;

import static com.chen.common.utils.AuthorityManagementUtil.checkVerticalAuth;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        Map<String, Object> claims = null;
        try {
            // 从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
//            System.out.println(redisToken);
            if (redisToken == null) {
                //为null说明token失效了
                throw new RuntimeException("token失效了");
            }

            claims = JwtUtil.parseToken(token);
            // 把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
//            return true;
        } catch (Exception e) {
            response.setStatus(401);
            log.error("登录拦截异常:{}", e.getMessage());
            return false;
        }

        // 权限校验
        try {
            String requestURI = request.getRequestURI();
            // 垂直越权校验
            if (!checkVerticalAuth(requestURI, claims)) {
                response.setStatus(403);
                log.error("越权拦截：用户角色无权访问该接口");
//                throw new RuntimeException("越权拦截：用户角色无权访问该接口");
                return false;
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException("越权:" + e.getMessage());
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
//        restHighLevelClient.close();
    }


//    /**
//     * 垂直权限校验
//     *
//     * @param claims 包含用户角色信息
//     */
//    private boolean checkVerticalAuth(HttpServletRequest request, Map<String, Object> claims) {
//        String requestURI = request.getRequestURI();
//        String userRole = null; // JWT中需存储角色字段
//        try {
//            userRole = claims.get("role").toString();
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
//
//        // 遍历权限配置
//        for (Map.Entry<String, List<String>> entry : API_ROLES.entrySet()) {
//            String pathPattern = entry.getKey();
//            List<String> allowedRoles = entry.getValue();
//
//            // 匹配当前请求路径
//            if (pathMatcher.match(pathPattern, requestURI)) {
//                // 无需登录的接口
//                if (allowedRoles.isEmpty()) return true;
//
//                // 校验角色权限
//                return allowedRoles.contains(userRole);
//            }
//        }
//
//        // 默认拒绝未配置的接口
//        return false;
//    }
}
